package com.itbour.web.action.trade;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.google.gson.Gson;
import com.itbour.com.page.Page;
import com.itbour.common.base.BaseAction;
import com.itbour.common.util.StringUtils;
import com.itbour.dto.com.UserInfoDto;
import com.itbour.dto.trade.InvoiceInfoDto;
import com.itbour.dto.trade.ItemInfoDto;
import com.itbour.dto.trade.OrderDetailInfoDto;
import com.itbour.dto.trade.OrderInfoDto;
import com.itbour.dto.trade.StateHisInfoDto;
import com.itbour.service.trade.InvoiceService;
import com.itbour.service.trade.ItemsService;
import com.opensymphony.xwork2.ActionContext;

/**
 * copyright Itbour team 2016
 * 
 * @author abby
 */

public class GetInvoiceWebAction extends BaseAction {

	private static final long serialVersionUID = 1L;

	private InvoiceService invoiceService;
	
	private String findFpState;     // 检索条件[商品状态]
	
	private String findFpNumber;	//检索条件[发票编号]
	
	private String findFpTitle;		//检索条件[发票抬头]
	
	private String findFpMobile;	//检索条件[手机号]
	
	private String delIds;
	// [商品]
	private HashMap<String, Object> invoiceMapResult = new HashMap<String, Object>();//[分页]商品信息列表
	private List<InvoiceInfoDto> invoiceInfoList;// 商品信息列表
	private InvoiceInfoDto invoiceInfo;// 更新用
	private String invId;// 发票id

	private String findPubFlg;// 检索条件[发布状态]
	private String ids;// 通用ids[逗号连接]
	private String order;// 显示顺序
	private StateHisInfoDto stateHisInfo;// 订单状态历史
	
	// 分页获取发票信息列表
	public String getInvoiceInfoPg() throws Exception {
		// 发票信息
		Map<String, Object> session = ActionContext.getContext().getSession();
    	UserInfoDto user = (UserInfoDto)session.get("user");
    	
		HttpServletRequest request = ServletActionContext.getRequest();
		String pageNumber = request.getParameter("page");
		String pageSize = request.getParameter("rows");
		
		Map<String, Object> param = new HashMap<String, Object>();
		if (StringUtils.isNotEmpty(findFpNumber)) {
			param.put("inv_no", "%"+findFpNumber+"%");
		}
		if (StringUtils.isNotEmpty(findFpTitle)) {
			param.put("title", "%"+findFpTitle+"%");
		}
		if (StringUtils.isNotEmpty(findFpMobile)) {
			param.put("mobile", findFpMobile);
		}
		if (StringUtils.isNotEmpty(findFpState)) {
			param.put("state", findFpState);
		}
		Page page = invoiceService.invoicePgQuery(param,
				Integer.parseInt(pageNumber),
				Integer.parseInt(pageSize));
		HashMap<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("total", page.getTotalCount());
		resMap.put("rows", page.getResult());
		//writeJSON(resMap);
		invoiceMapResult = resMap;
		return SUCCESS;
	}
	
	// 获取发票信息列表
	public String getInvoiceInfoLst() throws Exception {
		HttpServletRequest request = ServletActionContext.getRequest();
		Map<String, Object> param = new HashMap<String, Object>();
		String id = request.getParameter("inv_id");
		if (StringUtils.isNotEmpty(id)) {
			param.put("inv_id", id);
		}
		
		invoiceInfoList = invoiceService.selectInvoiceInfo(param);
		return SUCCESS;
	}
	
	
	// 更新发票信息列表
	public void updInvoice() throws Exception {
		if (invoiceInfo != null && 
			((invoiceInfo.getInv_id() != null && invoiceInfo.getInv_id()>0))) {
			Map<String, Object> session = ActionContext.getContext().getSession();
	    	UserInfoDto user = (UserInfoDto)session.get("user");
	    	
	    	Map<String, Object> param = new HashMap<String, Object>();
	    	if(invoiceInfo.getInv_id() != null && invoiceInfo.getInv_id()>0){
		    	param.put("inv_id", invoiceInfo.getInv_id());
	    	}
	    	if(invoiceInfo.getExpress() != null) {
	    		param.put("express", invoiceInfo.getExpress());
	    	}
	    	if(invoiceInfo.getTracking_no() != null) {
	    		param.put("tracking_no", invoiceInfo.getTracking_no());
	    	}
	    	if(invoiceInfo.getState() != null) {
	    		param.put("state", invoiceInfo.getState());
	    	}
	    	
	    	invoiceService.updInvoice(param);
		}
		this.writeJSON("ok");
	}
	
	//删除信息列表
	public void delInvoice() throws Exception {
		invoiceService.delInvoice(delIds);
		this.writeJSON("ok");
	}
	
	// 导出订单信息
	public void downInvoiceInfo() throws Exception{
		StringBuilder sb = new StringBuilder();
		String SEP = ",";
		
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		SimpleDateFormat format2 = new SimpleDateFormat("yyyyMMddHHmmss");
		String dataStr = format.format(date);
		String dataStr2 = format2.format(date);
		
		sb.append("示界港发票详情:").append(SEP).append(dataStr).append("\n");
		
		sb.append("发票ID")
		.append(SEP).append("发票编号")
		.append(SEP).append("发票抬头")
		.append(SEP).append("发票内容")
		.append(SEP).append("总金额")
		.append(SEP).append("纳税人识别号")
		.append(SEP).append("公司开户行")
		.append(SEP).append("公司银行账号")
		.append(SEP).append("公司地址")
		.append(SEP).append("手机号")
		.append(SEP).append("用户ID")
		.append(SEP).append("**填写的收货地址**")
		.append("\n");
		
		if(StringUtils.isNotEmpty(invId)){
			Map<String, Object> param = new HashMap<String, Object>();
			param.put("inv_id", invId);
			List<InvoiceInfoDto> oInfoLst = invoiceService.selectInvoiceInfo(param);
			if(oInfoLst!=null && oInfoLst.size()>0) {
				InvoiceInfoDto baseInfo = oInfoLst.get(0);
				
				List<InvoiceInfoDto> dInfoLst = invoiceService.selectInvoiceInfo(param);
				if(dInfoLst!=null && dInfoLst.size()>0){
					for(int i=0; i<dInfoLst.size(); i++) {
						InvoiceInfoDto dtlInfo = dInfoLst.get(i);
						String bankAccount = dtlInfo.getBank_account();
						if (bankAccount.matches("[0-9]+")){// 判断是否是纯数字
							bankAccount = "'"+bankAccount;
						}
						sb.append( "\""+Null2Str(baseInfo.getInv_id())+"\"" )
						.append(SEP).append( "\""+Null2Str(dtlInfo.getInv_no())+"\"" )
						.append(SEP).append( "\""+Null2Str(dtlInfo.getTitle())+"\"" )
						.append(SEP).append( "\""+Null2Str(baseInfo.getContent())+"\"" )
						.append(SEP).append( "\""+Null2Str(baseInfo.getTotal_fee().floatValue()/100)+"元\"" )
						.append(SEP).append( "\""+Null2Str(dtlInfo.getTaxpayer_id())+"\"" )
						.append(SEP).append( "\""+Null2Str(dtlInfo.getBank())+"\"" )
						.append(SEP).append( "\""+Null2Str(bankAccount)+"\"" )
						.append(SEP).append( "\""+Null2Str(dtlInfo.getAddress())+"\"" )
						.append(SEP).append( "\""+Null2Str(dtlInfo.getMobile())+"\"" )
						.append(SEP).append( "\""+Null2Str(dtlInfo.getUser_id())+"\"" )
						.append(SEP).append( "\""+Null2Str(dtlInfo.getAddr())+"\"" )
						.append("\n");
					}
				}
			}
		} else {
			sb.append("未获取到订单信息！\n");
		}
			
		String fileName = "ITB_ORDER_INFO_"+dataStr2+".csv";
		
        String output = sb.toString();
        HttpServletResponse response = ServletActionContext.getResponse();
        response.addHeader("Content-Disposition", "attachment; filename="+fileName); 
        response.setContentType("application/octet-stream"); 
        response.setCharacterEncoding("UTF8"); 
        response.getWriter().write(output); 
        response.flushBuffer();
	}
	
	private String Null2Str(Object in){
		return (in==null)?"":String.valueOf(in);
	}
	
	
	
	public InvoiceService getInvoiceService() {
		return invoiceService;
	}

	public void setInvoiceService(InvoiceService invoiceService) {
		this.invoiceService = invoiceService;
	}

	public HashMap<String, Object> getInvoiceMapResult() {
		return invoiceMapResult;
	}

	public void setInvoiceMapResult(HashMap<String, Object> invoiceMapResult) {
		this.invoiceMapResult = invoiceMapResult;
	}

	public List<InvoiceInfoDto> getInvoiceInfoList() {
		return invoiceInfoList;
	}

	public void setInvoiceInfoList(List<InvoiceInfoDto> invoiceInfoList) {
		this.invoiceInfoList = invoiceInfoList;
	}

	public InvoiceInfoDto getInvoiceInfo() {
		return invoiceInfo;
	}

	public void setInvoiceInfo(InvoiceInfoDto invoiceInfo) {
		this.invoiceInfo = invoiceInfo;
	}

	public String getInvId() {
		return invId;
	}

	public void setInvId(String invId) {
		this.invId = invId;
	}

	public String getFindPubFlg() {
		return findPubFlg;
	}

	public void setFindPubFlg(String findPubFlg) {
		this.findPubFlg = findPubFlg;
	}
	
	public String getIds() {
		return ids;
	}

	public void setIds(String ids) {
		this.ids = ids;
	}

	public String getFindFpNumber() {
		return findFpNumber;
	}

	public void setFindFpNumber(String findFpNumber) {
		this.findFpNumber = findFpNumber;
	}

	public String getFindFpTitle() {
		return findFpTitle;
	}

	public void setFindFpTitle(String findFpTitle) {
		this.findFpTitle = findFpTitle;
	}

	public String getFindFpMobile() {
		return findFpMobile;
	}

	public void setFindFpMobile(String findFpMobile) {
		this.findFpMobile = findFpMobile;
	}

	public String getDelIds() {
		return delIds;
	}

	public void setDelIds(String delIds) {
		this.delIds = delIds;
	}

	public String getFindFpState() {
		return findFpState;
	}

	public void setFindFpState(String findFpState) {
		this.findFpState = findFpState;
	}

	public StateHisInfoDto getStateHisInfo() {
		return stateHisInfo;
	}

	public void setStateHisInfo(StateHisInfoDto stateHisInfo) {
		this.stateHisInfo = stateHisInfo;
	}
	
	
	
}
